import { modal } from 'vue-strap'
import DatePicker from 'vue-datepicker'
import getDatePickerOption from '../../../util/date-picker-option'
import extend from 'extend'
import { showMsg, updateActivity, addActivity } from '../../../vuex/action'

const validation = {
  ac(data) {
    for (let name in data) {
      if ((data[name] + '').length === 0) {
        return '* 标记的均为必填/必选项'
      }
    }
    if (data.startTime >= data.endTime) {
      return '开始时间需早于结束时间'
    }
    if (data.title.length > 6) {
      return '按钮文案不能多于6个字'
    }
    return true
  }
}
const defaultData = {}

export default {
  name: 'Activity-configure',
  components: {
    'vue-modal': modal,
    'vue-date-picker': DatePicker
  },
  props: ['showConfigure', 'ac', 'isAdd', 'title'],
  data() {
    return {
      datePickerOption: getDatePickerOption()
    }
  },
  vuex: {
    actions: {
      xUpdateAc: updateActivity,
      xAddAc: addActivity,
      xShowMsg: showMsg
    }
  },
  ready() {
    if (this.isAdd) {
      defaultData.ac = extend(true, {}, this.ac)
    }
  },
  methods: {
    submit() {
      var ac = extend(true, {}, this.ac)

      var valid = validation.ac(ac)
      if (valid !== true) {
        return this.xShowMsg({
          type: 'danger',
          content: valid
        })
      }

      ac.gold = +ac.gold
      if (this.isAdd) {
        this.xAddAc(ac)
          .then(() => {
            this.ac = extend(true, {}, defaultData.ac)
            this.showConfigure = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      } else {
        this.xUpdateAc(ac)
          .then(() => {
            this.showConfigure = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      }
    }
  }
}
